import components from './helpers/components'
import { UserModel} from '/api/user-model.js';
import { ServiceModel} from './api/service-model';

App({
  components,
  onLaunch: function (res) {
    var _this = this;
    _this.globalData.appLaunch = res;
    _this.globalData.userModel = new UserModel();
    _this.globalData.serviceModel = new ServiceModel();
    _this.globalData.domain = this.globalData.serviceModel.$$prefix.replace("/api", "");
    wx.getSystemInfo({ success: function (res) { _this.globalData.statusBarHeight = res.statusBarHeight }})
    _this.globalData.userModel.getConfig().then(res => {
      _this.globalData.config = res.data
    })
    _this.globalData.pm = new Promise(resolve => {
      wx.getLocation({
        success(res) {
          _this.globalData.locationInfo = res;
          _this.getUserInfo(function(){
            resolve()
          })
        }
      })
    })
  },
  getUserInfo: function (callBack) {
    const _this = this
      if (this.globalData.userInfo) {
        typeof callBack == "function" && callBack(this.globalData.userInfo)
      } else {//调用登录接口
        wx.login({
          success: function (res) {
            _this.globalData.userModel.getUserByCode({
              data: { code: res.code}
            }).then(json => {
              const { session_key, id} = json.data
              wx.getUserInfo({
                success: function (res) {
                  var scene = _this.globalData.appLaunch.query.scene;
                  _this.globalData.userModel.userAuth({
                    data: {
                      'session_key': session_key,
                      'encryptedData': res.encryptedData,
                      'iv': res.iv,
                      'stid': scene ? scene : 0,
                      'contact_addr_lat': _this.globalData.locationInfo.latitude,
                      'contact_addr_lng': _this.globalData.locationInfo.longitude
                    }
                  }).then(json => {
                    _this.globalData.userInfo = json.data
                    _this.globalData.curStore = json.data.store
                    wx.setStorageSync('token', json.data.token);
                    typeof callBack == "function" && callBack(_this.globalData.userInfo)
                  });
                },fail: function (res) {
                  wx.navigateTo({ url: '/pages/person/authorize/authorize', })
                }
              })
            })
          }
        })
      }
  },
  globalData: {
    userInfo: null,
    userModel: null,
    serviceModel: null,
    curStore: {},
    imageList: [], //选择的图片列表
    docList: [], //上传的文档列表
    statusBarHeight:0,
    address: {},
  },
})